import { computed, Ref } from "vue";
import { getworkOrderPageDataApi, getworkOrderPageStatApi, workOrderExcelApi } from "@/api/waybillManagement/workOrder";
import CommonHook from "@/hook/commonHook";
import dayjs from "dayjs";
import { message } from "ant-design-vue";

export default function OperationHook(state: {
  activeKey: Ref<string>;
  searchForm: WorkOrder.SearchForm;
  loading: Ref<boolean>;
  tableData: Ref<WorkOrder.ListRows[]>;
  pageStat: Ref<Base.GeneraDataType>;
  tableRef: Ref<any>;
  drawerOpts: Base.DrawerOpts;
  dialogOpts: Base.DialogOpts;
}) {
  const { activeKey, searchForm, loading, tableData, pageStat, drawerOpts, tableRef, dialogOpts } = state;
  const selectRows = computed<Array<WorkOrder.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const { getNoZeroKey } = CommonHook();
  const getData = async () => {
    const params = {
      ...getParams()
    };

    loading.value = true;
    return getworkOrderPageDataApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const pageStateic = () => {
    const params = {
      ...getParams()
    };
    Reflect.deleteProperty(params, "statusList");
    return getworkOrderPageStatApi(params).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        Object.assign(pageStat.value, {
          1: data[1],
          2: data[2],
          3: data[3],
          4: data[4]
        });

        activeKey.value = String(getNoZeroKey(pageStat.value, ["1", "2", "3", "4"]));
      }
    });
  };

  const getParams = () => {
    const {
      pageNum,
      pageSize,
      total,
      beforePageNum,
      workOrderNo,
      depositTime,
      waybillNumList,
      questionTypeList,
      shipmentLimit,
      outWarehouseBrokerIdList,
      channelIdList,
      bizIdList,
      selectStatusList,
      createByList
    } = searchForm;
    const params: Parameters<typeof getworkOrderPageDataApi>[0] = {
      pageNum,
      pageSize,
      total,
      beforePageNum,
      workOrderNo,
      createTimeStart: depositTime.length ? dayjs(depositTime[0]).startOf("day").format("YYYY-MM-DD HH:mm:ss") : undefined,
      createTimeEnd: depositTime.length ? dayjs(depositTime[1]).startOf("day").format("YYYY-MM-DD HH:mm:ss") : undefined,
      waybillNumList: [],
      questionTypeList,
      statusList: [activeKey.value],
      shipmentLimit,
      outWarehouseBrokerIdList,
      selectStatusList,
      createByList,
      channelIdList,
      bizIdList
    };
    if (waybillNumList)
      params.waybillNumList = waybillNumList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (channelIdList.length) {
      params.channelIdList = channelIdList.map((t: any) => t[t.length - 1]);
    }

    if (questionTypeList.length) {
      params.questionTypeList = questionTypeList.reduce((acc: Array<["PRE_PORT_SCOPE" | "AFTER_PORT_SCOPE", ...string[]]>, [key, value]) => {
        let targetArray = acc.find(item => item[0] === key);

        if (!targetArray) {
          targetArray = [key];
          acc.push(targetArray);
        }

        targetArray.push(value);

        return acc;
      }, []);
    }

    if (searchForm.sort) {
      params.order = searchForm.order;
      params.sort = searchForm.sort;
    }
    return params;
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    await pageStateic();
    getData();
  };

  const changeTabHandle = () => {
    searchForm.pageNum = 1;
    getData();
  };

  // 更新进度
  const detailHandle = (row: Base.GeneraDataType) => {
    drawerOpts.width = "1200px";
    drawerOpts.title = "更新进度";
    drawerOpts.type = 1;
    drawerOpts.passData = row;
    drawerOpts.component = "Detail";
    drawerOpts.visible = true;
  };
  //更改问题类型
  const importBoxTransferNoHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选数据");
    const transportNum = Array.from(new Set(selectRows.value.map((t: any) => t.questionScope)));
    if (transportNum.length > 1) return message.error("仅支持选择同一问题范围的工单进行操作");
    dialogOpts.title = `更改问题类型`;
    dialogOpts.width = "520px";
    dialogOpts.component = "ModifyWorkOrderStatus";
    dialogOpts.passData = selectRows.value;
    dialogOpts.type = selectRows.value[0].questionScope === "PRE_PORT_SCOPE" ? 1 : 2;
    dialogOpts.visible = true;
  };
  //导出
  const exportHandle = () => {
    loading.value = true;
    const params = {
      ...getParams(),
      idList: selectRows.value.length ? selectRows.value.map(({ id }) => id) : undefined
    };
    return workOrderExcelApi(params)
      .then((res: any) => {
        const { code } = res;
        if (code === 200) {
          message.success("创建任务成功，请前往导出中心下载！");
          searchHandle();
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };

  return {
    getData,
    searchHandle,
    changeTabHandle,
    detailHandle,
    importBoxTransferNoHandle,
    exportHandle
  };
}
